package com.guigu.gulicommon.context;

import com.guigu.gulicommon.entity.pojo.UserLoginInfoPoJo;

/**
 * 用户信息上下文
 *
 * @author 陈俊杰
 * @version 1.0
 * @since 2024/8/14 23:55
 */
public class UserContext {
    private final InheritableThreadLocal<UserLoginInfoPoJo> threadLocal;


    private UserContext() {
        this.threadLocal = new InheritableThreadLocal<>();
    }


    public static UserContext getInstance() {
        return SingletonHolder.instance;
    }

    /**
     * 设置用户数据
     *
     * @param userId 用户id
     */
    public void setCurrentUser(String userId) {
        UserLoginInfoPoJo userLoginInfoPoJo = new UserLoginInfoPoJo().setId(Long.valueOf(userId));
        this.threadLocal.set(userLoginInfoPoJo);
    }

    public void setCurrentUser(String userId, String token) {
        UserLoginInfoPoJo userLoginInfoPoJo = new UserLoginInfoPoJo()
                .setId(Long.valueOf(userId))
                .setToken(token);
        this.threadLocal.set(userLoginInfoPoJo);
    }

    /**
     * 获取当前用户
     *
     * @return userId
     */
    public UserLoginInfoPoJo getCurrentUser() {
        return this.threadLocal.get();
    }

    /**
     * 清理用户信息
     */
    public void clear() {
        this.threadLocal.remove();
    }

    // 静态内部类，持有单例实例
    private static class SingletonHolder {
        // 静态成员变量，使用volatile关键字确保可见性和有序性
        private static final UserContext instance = new UserContext();
    }
}
